/*
*  Node.cpp
*  SypXIPhone
*
*  Created by Luv Khemani on 5/13/10.
*  Copyright 2010 Luv Khemani. All rights reserved.
*
*/

#include <algorithm>

#ifdef SYPX_MEMCHECK
#include "mmgr.h"
#endif

#include "Node.h"

namespace SypX
{
	Node::Node():parent(0)
	{

	}

	Node::~Node()
	{

	}

	void Node::setParent(Node* p)
	{		
		if(p)
		{			
			p->children.push_back(this);
		}
		else
		{//0 passed in, must remove self from existing parent's list
			if(parent)
			{//if we have an existing parent				
				parent->children.erase( std::find(parent->children.begin(), parent->children.end(), this) );
			}
		}
		parent = p;
	}

	void Node::offsetPosition(const SypX::Vec3& pos)
	{
		transform[3].x += pos.x;
		transform[3].y += pos.y;
		transform[3].z += pos.z;
		for(unsigned int i = 0; i < children.size(); ++i)
		{
			children[i]->offsetPosition(pos);
		}
	}

	void Node::offsetPosition(const SypX::Vec2& pos)
	{
		transform[3].x += pos.x;
		transform[3].y += pos.y;
		for(unsigned int i = 0; i < children.size(); ++i)
		{
			children[i]->offsetPosition(pos);
		}
	}

	void Node::setPosition(const SypX::Vec3& pos)
	{
		Vec3 p(transform[3]);
		offsetPosition( Vec3(pos-p) );		
	}

	void Node::setPosition(const SypX::Vec2& pos)
	{
		Vec2 p(transform[3]);
		offsetPosition( Vec2(pos-p) );				
	}

	const Mat4& Node::getTransformMatrix()
	{
		return transform;
	}

	const Vec4& Node::getPositionRef()
	{
		return transform[3];
	}
}